<template>
	<view class="container">
		<view class="tui-line-cell-img">
			<view class="tui-upload-box">
				<view class="tui-upload-item" v-if="groupCoverFile != ''"><image :src="groupCoverFile" 
				class="tui-upload-img" @tap="toCoverSelect" mode="aspectFill"></image></view>
				<view class="tui-upload-item" v-if="groupCoverFile == ''" hover-class="tui-opcity" :hover-stay-time="150" @tap="toCoverSelect">
					<text class="tui-upload-item-text">上传封面</text>
				</view>
			</view>
		</view>
		<form @submit="formSubmit" @reset="formReset">
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">群分类</view>
					<view class="uni-list-cell-db">
						<picker @change="bindPickerChange" :value="selectTypeIndex" :range="typeList" range-key="title">
							<view class="uni-input">{{ typeList[selectTypeIndex].title }}</view>
						</picker>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">群主题</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="itemObj.groupTitle" name="groupTitle" placeholder="请输入群主题" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			
			<tui-list-cell :hover="false">
				<view class="tui-line-cell-img-group">
					<view class="tui-title">群二维码</view>
					<view class="tui-upload-box">
						<view class="tui-upload-item-group" v-if="groupImgFile != ''">
							<image lazy-load="true" :src="groupImgFile" class="tui-upload-img" @tap="chooseImage" mode="aspectFit"></image>
						</view>
						<view class="tui-upload-item-group" v-if="groupImgFile == ''" hover-class="tui-opcity" :hover-stay-time="150" @tap="chooseImage">
							<text class="tui-upload-item-text">上传</text>
						</view>
					</view>
				</view>
			</tui-list-cell>

			<!-- 时间控件 -->
			<tui-list-cell @tap="showEndTime()" hover-class="opcity" :hover-stay-time="150">
				<view class="tui-line-cell">
					<view class="tui-title">过期时间</view>
					<view class="tui-title-value">
						<text>{{ endTime }}</text>
					</view>
				</view>
			</tui-list-cell>

			<tui-list-cell @tap="chooseLocation()" hover-class="opcity" :hover-stay-time="150">
				<view class="tui-line-cell">
					<view class="tui-title">群活动地</view>
					<view class="tui-title-value">
						<text>{{ locationAddress }}</text>
					</view>
				</view>
			</tui-list-cell>

			<view class="tui-btn-box">
				<button class="btn-primary" hover-class="btn-hover" formType="submit" type="primary">下一步</button>
				<!-- <button class="btn-primary btn-gray" hover-class="btn-gray-hover" formType="reset">重置</button> -->
			</view>
		</form>
		<tui-datetime
			ref="endTime"
			:type="1"
			:startYear="startYear"
			:endYear="endYear"
			:cancelColor="cancelColor"
			:color="color"
			:setDateTime="setDateTime"
			@confirm="changeTimeEnd"
		></tui-datetime>
	</view>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
const form = require('../../components/utils/formValidation.js');
import tuiListCell from '@/components/list-cell/list-cell';
import tuiDatetime from '@/components/dateTime/dateTime';
const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
export default {
	components: {
		tuiListCell,
		tuiDatetime
	},
	computed: {
		// ...mapState(['userInfo'])
		...mapState({
		})
	},
	data() {
		return {
			$cdn:this.$cdn,
			groupImgFile: '',
			groupImgFilePath: '',
			
			// 群封面
			groupCoverFile:'',
			groupCoverFilePath:'',

			startYear:2020,
			endYear: 2030,
			cancelColor: '#888',
			color: '#5677fc',
			setDateTime: '2020-01-01 23:00:00',
			endTime: '请选择',

			selectTypeIndex: 0,
			typeList: [{ title: '请选择', groupTypeId: 0 }],
			itemObj: {},
			qqmapsdk: null,
			latitude:  '',
			longitude: '',
			locationAddress: '请选择',
			cityCode:'',
			// 当前页面是否已定位，如为默认取首页的定位信息
			hasLocation: false,
			// 编辑时用
			groupId:''
		};
	},
	onLoad: function(data) {
		this.qqmapsdk = new QQMapWX({
			key: 'W4WBZ-TUD65-IDAIR-QPM36-HMFQ5-CGBZP'
		});
		if(data.coverFile){
			this.groupCoverFile=data.coverFile;
		}
		if(data.coverFilePath){
			this.groupCoverFilePath=data.coverFilePath;
		}
		// groupId 如有则是编辑模式
		if(data.groupId){
			this.groupId=data.groupId;
		}
		this.getGroupTypeList();
	},
	created() {
		
	},
	methods: {
		// 判断是否进入详情修改页面
		isEditDesc(){
			if(this.groupImgFile==this.$cdn.groupQR+this.itemObj.qrcode){
				return true;
			}else{
				return false;
			}
		},
		// 是否修改封面
		isEditCoverImg(){
			if(this.groupCoverFile==this.$cdn.groupCover+this.itemObj.coverImg || this.groupCoverFile.indexOf('default')>0){
				return false;
			}else{
				return true;
			}
		},
		// 是否修改二维码
		isEditQrcode(){
			if(this.groupImgFile==this.$cdn.groupQR+this.itemObj.qrcode){
				return false;
			}else{
				return true;
			}
		},
		indexVf: function(arr,target) {
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].groupTypeId == target) {
					return i;
				}
			}
		},
		geGroupDetail(groupId) {
			let postData = { groupId: groupId };
			this.tui
				.request('/api/group/get', postData, 'POST', false, false)
				.then(res => {
					if (res.code == 0) {
						console.log('geGroupDetail=' + JSON.stringify(res));
						// this.itemObj = res.data.group;
						let dbData = res.data.group;
						// 从db获取数据显示到页面
						this.itemObj.groupId=dbData.groupId;
						this.itemObj.groupTitle=dbData.groupTitle;

						// 封面,如是封面选择页面跳转过来，则显示选择的封面图
						if(this.groupCoverFile==''){
							this.groupCoverFile=this.$cdn.groupCover+dbData.coverImg;
							this.groupCoverFilePath=dbData.coverImg;
							this.itemObj.coverImg=dbData.coverImg;
						}
						
						// 群二维码
						this.groupImgFile=this.$cdn.groupQR+dbData.qrcode;
						this.groupImgFilePath=dbData.qrcode;
						this.itemObj.qrcode=dbData.qrcode;
						
						// 通过groupTypeId找到集合typeList中groupTypeId=当前groupTypeId的值，所在的坐标
						this.selectTypeIndex=this.indexVf(this.typeList,dbData.groupTypeId);
						console.log('this.selectTypeIndex='+this.selectTypeIndex);
						this.endTime=dbData.endTime;
						
						this.longitude=dbData.lng;
						this.latitude=dbData.lat;
						this.locationAddress=dbData.place;
						this.cityCode=dbData.cityCode;
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		// 获取聚会分类列表
		getGroupTypeList() {
			//参数
			let postData = {};
			this.tui
				.request('/api/groupType/getGroupTypeList', postData, 'GET', false, true)
				.then(res => {
					if (res.code == 0) {
						this.typeList=res.data;
						if(this.groupId){
							this.geGroupDetail(this.groupId);
						}
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		toCoverSelect(){
			uni.navigateTo({
				url:'/pages/group/cover-select?groupId='+this.groupId
			});
		},
		chooseGroupCoverImage: function(e) {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					console.log(JSON.stringify(res));
					that.groupCoverFile = res.tempFilePaths[0];
					/* that.tui.reSizeImg(res.tempFilePaths[0], 456 * 1.5, 236 * 1.5, function(resImg) {
						that.actFile = resImg;
					}); */
				}
			});
		},
		// 上传封面
		uploadGroupCoverImage() {
			if(this.isEditCoverImg()){
				this.tui
					.uploadFile('/auth/api/group/uploadCoverImg', this.groupCoverFile)
					.then(res => {
						console.log('uploadCoverImg上传结果' + JSON.stringify(res));
						if (res.code == 0) {
							this.groupCoverFilePath = res.data;
							// return callback(res);
							this.uploadImg();
						}
					})
					.catch(res => {
						console.log(res);
					});
			}else{
				this.uploadImg();
			}
		},
		chooseImage: function(e) {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					console.log(JSON.stringify(res));
					that.groupImgFile = res.tempFilePaths[0];
					/* that.tui.reSizeImg(res.tempFilePaths[0], 456 * 1.5, 236 * 1.5, function(resImg) {
						that.actFile = resImg;
					}); */
				}
			});
		},
		uploadImg() {
			if(this.isEditQrcode()){
				this.tui
					.uploadFile('/auth/api/group/uploadQRcode', this.groupImgFile)
					.then(res => {
						console.log('uploadCoverImg上传结果' + JSON.stringify(res));
						if (res.code == 0) {
							this.groupImgFilePath = res.data;
							this.save();
						}
					})
					.catch(res => {
						console.log(res);
					});
				}else{
					this.save();
				}
		},
		// 后端保存接口
		save: function() {
			// 不管新增还是修改过，重新赋值一遍
			this.itemObj.coverImg = this.groupCoverFilePath;
			this.itemObj.qrcode = this.groupImgFilePath;
			this.itemObj.groupTypeId = this.typeList[this.selectTypeIndex].groupTypeId;
			this.itemObj.endTimeStr = this.endTime;
			this.itemObj.lng = this.longitude;
			this.itemObj.lat = this.latitude;
			this.itemObj.place = this.locationAddress;
			this.itemObj.cityCode = this.cityCode;

			this.tui
				.request('/auth/api/group/save', this.itemObj, 'POST', false, false)
				.then(res => {
					if (res.code == 0) {
						console.log('save' + JSON.stringify(res));
						// 页面跳转
						if(this.isEditDesc()){
							uni.navigateTo({
								url:'/pages/group/group-edit-desc?type=edit&groupId='+res.data.groupId
							})
						}else{
							uni.navigateTo({
								url:'/pages/group/group-edit-desc?groupId='+res.data.groupId
							})
						}
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'error'
						});
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		formSubmit: function(e) {
			// 图片校验
			if (this.groupCoverFile == undefined || this.groupCoverFile == '') {
				uni.showToast({
					title: '请上传封面图片',
					icon: 'error'
				});
				return false;
			}
			if (this.typeList[this.selectTypeIndex].groupTypeId == 0) {
				uni.showToast({
					title: '请选择分类',
					icon: 'error'
				});
				return false;
			}
			// 图片校验
			if (this.groupImgFile == undefined || this.groupImgFile == '') {
				uni.showToast({
					title: '请上传群二维码',
					icon: 'error'
				});
				return false;
			}
			if (this.endTime == '请选择') {
				uni.showToast({
					title: '请选择过期时间',
					icon: 'error'
				});
				return false;
			}
			if (this.locationAddress == undefined || this.locationAddress == '请选择') {
				uni.showToast({
					title: '请选择群活动地点',
					icon: 'error'
				});
				return false;
			}
			// 表单规则
			let rules = [
				{
					name: 'groupTitle',
					rule: ['required', 'minLength:4', 'maxLength:100'], //可使用区间，此处主要测试功能
					msg: ['请输入主题', '主题必须4个或以上字符', '主题不能超过100个字符']
				}
			];
			// 进行表单检查
			let formData = e.detail.value;
			console.log('formData=' + JSON.stringify(formData));
			let checkRes = form.validation(formData, rules);
			if (!checkRes) {
				// 调用后端接口保存，先上传图片再保存数据
				// 如修改，则判断是否更改图片
				this.uploadGroupCoverImage();
			} else {
				uni.showToast({
					title: checkRes,
					icon: 'none'
				});
			}
		},
		formReset: function(e) {
			console.log('清空数据');
		},
		// 日期控件
		showEndTime: function() {
			this.$refs.endTime.show();
		},
		changeTimeEnd: function(e) {
			console.log(e);
			this.endTime = e.result;
		},
		// 选择位置
		chooseLocation: function() {
			let that=this;
			uni.chooseLocation({
				success: res => {
					console.log(JSON.stringify(res));
					that.hasLocation = true;
					that.longitude=res.longitude;
					that.latitude=res.latitude;
					that.locationAddress = res.name;
					// 根据经纬度，获取城市city_code
					// 根据经纬度获取地址信息
					that.qqmapsdk.reverseGeocoder({
						location: {
							latitude:  res.latitude,
							longitude: res.longitude
						},
						success: resTwo => {
							console.log(JSON.stringify(resTwo));
							that.cityCode=resTwo.result.ad_info.adcode;
						},
						fail: res => {
							// this.address = '获取位置信息失败';
						}
					});
				}
			});
		},
		clear: function() {
			this.hasLocation = false;
		},
		bindPickerChange: function(e) {
			console.log('picker发送选择改变，携带值为：' + e.target.value);
			this.selectTypeIndex = e.target.value;
			// 展示默认的封面图
			/* if(this.groupCoverFile=='' || this.groupCoverFile.indexOf('default')>0){
				let defaultPath='default/type_'+this.typeList[this.selectTypeIndex].groupTypeId+'.jpg';
				this.groupCoverFile=this.$cdn.groupCover+defaultPath;
				this.groupCoverFilePath=defaultPath;
			} */
		}
	}
};
</script>

<style>
/* @import '../../static/style/thorui.css'; */
.container {
	padding: 0rpx 0 10rpx 0;
}

.tui-line-cell {
	width: 100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.tui-title {
	line-height: 32rpx;
	flex-shrink: 0;
}

.tui-input {
	font-size: 32rpx;
	color: #333;
	padding-left: 20rpx;
	flex: 1;
}

.radio-group {
	margin-left: auto;
	transform: scale(0.8);
	transform-origin: 100% center;
	flex-shrink: 0;
}

.tui-radio {
	display: inline-block;
	padding-left: 28rpx;
	font-size: 36rpx;
	vertical-align: middle;
}

.tui-btn-box {
	padding: 40rpx 50rpx;
	box-sizing: border-box;
}

.btn-gray {
	margin-top: 30rpx;
}

.tui-tips {
	padding: 30rpx;
	color: #999;
	font-size: 24rpx;
}

.tui-upload-box {
	flex-flow: column;
	width: 100%;
	height: 100%;
}
.tui-line-cell-img {
	display: flex;
	height: 390rpx;
	width: 100%;
}
.tui-upload-item {
	width: 100%;
	height: 390rpx;
	border: 1rpx solid #e6e6e6;
	box-sizing: border-box;
	border-radius: 4rpx;
}
.tui-line-cell-img-group {
	display: flex;
	width: 50%;
}
.tui-upload-item-group {
	height: 200rpx;
	border: 1rpx solid #e6e6e6;
	box-sizing: border-box;
	border-radius: 4rpx;
	margin-left: 20rpx;
}
.tui-upload-item-text {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}
.tui-upload-img {
	width: 100%;
	height: 100%;
}

.tui-title-value {
	margin-left: 30rpx;
	width: 100%;
}
</style>
